//
//  OrbitCam.m
//  CompGraf2
//
//  Created by Juan Niosi on 30/08/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "OrbitCam.h"
#import "Engine.h"

@implementation OrbitCam

@synthesize distance, minDist, maxDist, offset;

- (id)init:(Engine *)engine
{
    self = [super init:engine];
    if (self) {
        GLfloat *pos = malloc(sizeof(GLfloat)*3);
        pos[0] = 0.0f;
        pos[1] = 0.0f;
        pos[2] = 0.0f;
        
        position = pos;
        
        GLfloat *rot = malloc(sizeof(GLfloat)*3);
        rot[0] = 0.0f;
        rot[1] = 0.0f;
        rot[2] = 0.0f;
        
        rotation = rot;
        
        GLfloat *ofst = malloc(sizeof(GLfloat)*3);
        ofst[0] = 0.0f;
        ofst[1] = -2.0f;
        ofst[2] = 0.0f;
        
        offset = ofst;
        
        distance = -5.0f;
        
        minDist = -15.0f;
        maxDist = -5.0f;
        
        minX = 0.0f;
        maxX = 90.0f;
    }
    
    return self;
}

- (void)drawPos:(Engine *)engine
{
    [engine set_transform];
    glLoadIdentity();
    
    [engine translateZ:distance];
    [engine rotate:rotation];
    [engine translate:position];
    [engine translate:offset];
    
    GLfloat *lightPos1 = malloc(sizeof(GLfloat)*4);
    lightPos1[0] = 0.0f;
    lightPos1[1] = 30.0f;
    lightPos1[2] = 0.0f;
    lightPos1[3] = 1.0f;
    
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos1);
    
    planes = [self getCameraPlanes];
}

- (void)translate:(GLfloat *)translation
{
    position[0] += translation[0];
    position[1] += translation[1];
    position[2] += translation[2];
}

- (void)zoom:(GLfloat)dist
{
    distance += dist;
    
    if (distance < minDist)
    {
        distance = minDist;
    }
    else if (distance > maxDist)
    {
        distance = maxDist;
    }
}

- (void)rotate:(GLfloat *)rot
{
    rotation[0] += rot[0];
    rotation[1] += rot[1];
    rotation[2] += rot[2];
    
    if (rotation[0] < minX)
        rotation[0] = minX;
    else if (rotation[0] > maxX)
        rotation[0] = maxX;
}

- (void)rotateX:(GLfloat )rot
{
    rotation[0] += rot;
    
    if (rotation[0] < minX)
        rotation[0] = minX;
    else if (rotation[0] > maxX)
        rotation[0] = maxX;
}

- (void)rotateY:(GLfloat )rot
{
    rotation[1] += rot;
}
- (void)rotateZ:(GLfloat )rot
{
    rotation[2] += rot;
}
- (void)reset:(Engine *)engine
{
    [engine reset_transform];
}

- (void)dealloc
{
    free(offset);
    [super dealloc];
}
@end
